package com.niuwa.p2p.service.impl.claimtransfer;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.niuwa.p2p.core.mvc.entity.JsonResult;
import com.niuwa.p2p.core.utils.DictConstant;
import com.niuwa.p2p.core.utils.DictConstant.ProductIdType;
import com.niuwa.p2p.core.utils.StringUtil;
import com.niuwa.p2p.dao.business.CustClaimDao;
import com.niuwa.p2p.dao.business.ProdRelativeProtDao;
import com.niuwa.p2p.dao.claimtransfer.TransApplyLogDao;
import com.niuwa.p2p.dao.claimtransfer.TransProductDao;
import com.niuwa.p2p.dao.claimtransfer.TransferApplyDao;
import com.niuwa.p2p.dao.productTemplate.ProductDao;
import com.niuwa.p2p.dao.productTemplate.ProductTemplateDao;
import com.niuwa.p2p.entity.business.CustClaim;
import com.niuwa.p2p.entity.business.ProdRelativeProt;
import com.niuwa.p2p.entity.claimtransfer.TransApplyLog;
import com.niuwa.p2p.entity.claimtransfer.TransProduct;
import com.niuwa.p2p.entity.claimtransfer.TransferApply;
import com.niuwa.p2p.entity.productTemplate.Product;
import com.niuwa.p2p.entity.productTemplate.ProductProtocol;
import com.niuwa.p2p.entity.productTemplate.ProductTemplate;
import com.niuwa.p2p.service.claimtransfer.ITransferApplyService;
import com.niuwa.p2p.service.productTemplate.ITransProdTemplateService;
import com.niuwa.p2p.service.productTemplate.ProductService;
import com.niuwa.p2p.vo.business.ClaimDetailVo;
import com.niuwa.p2p.vo.productTemplate.TransProdTmptForm;
import com.niuwa.p2p.vo.productTemplate.TransProdTmptVo;

/**
 * 债权申请
 * @author Dell
 *
 */
@Service
public class TransferApplyServiceImpl implements ITransferApplyService {
	
	@Autowired
	TransApplyLogDao transApplyLogDao;
	
	@Autowired
	TransferApplyDao transferApplyDao;
	
	@Autowired
	TransProductDao transProductDao;
	
	@Autowired
	CustClaimDao custClaimDao;
	
	@Autowired
	ProductDao productDao;
	
	@Autowired
	ProductTemplateDao productTemplateDao;
	
	@Autowired
	private ProdRelativeProtDao prodRelativeProtDao;
	
	@Autowired
	ITransProdTemplateService templateService;
	
	@Autowired
	private ProductService productService;

	@Override
	public JsonResult addPassClaim(Long userId, String serialNo) {
		JsonResult jsonResult=new JsonResult(false,"通过失败!");
		//影响行数
		int result = 0;
		try {
			//根据债权申请编号查询信息
			TransferApply transferApply = transferApplyDao.selectTransferApplyBySerialNo(serialNo);
			if(!"".equals(transferApply) && transferApply != null){
				if(DictConstant.TranferStatus.RELEASED.getCode().equalsIgnoreCase(transferApply.getTranferStatus())){
					//添加债权申请操作日志
					result = addaAplyLog(userId, null, transferApply,"PASSED");
					if(result > 0){
						//查询相关产品信息
						Map<String, Object> paramMap = new HashMap<String, Object>();
						paramMap.put("productCode", transferApply.getProdCode());
						ClaimDetailVo claimDetailVo = productDao.getClaimDetail(paramMap);
						//查询转让者债权信息
						CustClaim custClaim = custClaimDao.selectCustClaimByCreditNo(transferApply.getCreditNo());
						if(claimDetailVo != null){
							//直投类产品编码
							String prodCode = productService.getNewProductId(ProductIdType.CPDT);
							//添加债权转让产品
							result = addaTransProduct(userId, prodCode, transferApply, claimDetailVo, custClaim);
							if(result > 0){
								//添加产品信息相关信息(包括协议关联表)
								result = addaProduct(userId, prodCode, claimDetailVo);
								if(result > 0){
									//更新转让者债权状态为转让中(p2p_cust_claim)
									CustClaim claim = new CustClaim();
									claim.setCreditNo(custClaim.getCreditNo());
									claim.setCreditStatus(DictConstant.CreditTransStatus.TRANSFERRING.getCode());
									result = custClaimDao.updateByPrimaryKeySelectiveByVersion(claim);
									if(result > 0){
										//更新转让状态(根据自转债权流水号更新转让状态)
										TransferApply apply = new TransferApply();
										apply.setSerialNo(serialNo);
										apply.setTranferStatus(DictConstant.TranferStatus.RELEASED.getCode());
										result = transferApplyDao.updateStatusBySerialNo(apply);
										if(result > 0){
											jsonResult=new JsonResult(true,"操作成功");
										}else{
											jsonResult=new JsonResult(false,"更新转让状态失败");
										}
									}else{
										jsonResult=new JsonResult(false,"更新转让状态失败");
									}
								}else{
									jsonResult=new JsonResult(false,"添加产品相关信息失败");
								}
							}else{
								jsonResult=new JsonResult(false,"添加债权转让产品失败");
							}
						}else{
							jsonResult=new JsonResult(false,"项目信息为空");
						}
					}else{
						jsonResult=new JsonResult(false,"添加债权申请操作日志失败");
					}
				}else{
					jsonResult=new JsonResult(false,"已经发布，不可重复审核");
				}
			}else{
				jsonResult=new JsonResult(false,"不存在该债权申请");
			}
		} catch (Exception e) {
			jsonResult=new JsonResult(false,"通过异常!");
		}
		return jsonResult;
	}
	
	/**
	 * 添加债权申请操作日志
	 * @param userId
	 * @param transferApply
	 * @return
	 */
	public int addaAplyLog(Long userId, String remark, TransferApply transferApply, String type) {
		//影响行数
		int result = 0;
		if(transferApply != null){
			TransApplyLog applyLog = new TransApplyLog();
			applyLog.setOperator(userId);
			applyLog.setRemark(remark);
			applyLog.setCreateTime(new Date());
			if("NO_PASS".equals(type)){
				applyLog.setOperateType(DictConstant.TransOperateType.REJECT.getCode());
			}
			if("PASSED".equals(type)){
				applyLog.setOperateType(DictConstant.TransOperateType.PASSED.getCode());
			}
			applyLog.setSerialNo(transferApply.getSerialNo());
			result = transApplyLogDao.insertSelective(applyLog);
		}
		return result;
	}
	
	/**
	 * 添加债权转让产品
	 * @param userId
	 * @param transferApply
	 * @param claimDetailVo
	 * @return
	 */
	public int addaTransProduct(Long userId, String prodCode, TransferApply transferApply, ClaimDetailVo claimDetailVo, CustClaim custClaim) {
		//CustClaim custClaim = custClaimDao.selectCustClaimByCreditNo(transferApply.getCreditNo());
		//影响行数
		int result = 0;
		if(claimDetailVo != null && transferApply != null &&  custClaim != null){
			TransProduct transProduct = new TransProduct();
			transProduct.setProdCode(prodCode);
			transProduct.setAmount(transferApply.getTransferCapital());
			transProduct.setCreditNo(transferApply.getCreditNo());
			transProduct.setSeller(custClaim.getCustId());
			transProduct.setYearRate(transferApply.getYearRate());
			transProduct.setProjectNo(transferApply.getProjectCode());
			//转让费率类型转换(double转为bigDecimal)
			BigDecimal transferRate = new BigDecimal(claimDetailVo.getTransRate());
			transProduct.setTransferRate(transferRate);
			transProduct.setPrice(transferApply.getTransferPrice());
			transProduct.setTransferProdType(claimDetailVo.getProdKind());
			transProduct.setAccruedInterest(transferApply.getAccruedInterest());
			transProduct.setDiscount(transferApply.getDiscount());
			result = transProductDao.insertSelective(transProduct);
		}
		return result;
	}
	
	/**
	 * 添加产品信息和协议关联表
	 * 
	 * @return
	 */
	public int addaProduct(Long userId, String prodCode, ClaimDetailVo claimDetailVo) {
		//影响行数
		int result = 0;
		if(claimDetailVo != null){
			//获取最新有效的债权转让模板信息
			ProductTemplate productTemplate = productTemplateDao.selectLatestProTemplate();
			if(productTemplate != null){
				//最新模板ID
				long tempId = productTemplate.getTempId();
				//获取模板相关信息
				TransProdTmptVo prod = templateService.getProdTmptById(tempId);
				if(prod != null){
					//协议信息
					List<ProductProtocol> productProtocols = prod.getPpList();
					//模板信息
					TransProdTmptForm tmptForm = prod.getTmptForm();
					if(tmptForm != null){
						try {
							Product product = new Product();
							Date time = new Date();
							product.setProductCode(prodCode);//产品编号
							product.setProductName(claimDetailVo.getProductName());//产品名称
							product.setProdDesc(claimDetailVo.getProdDesc());//产品简介
							product.setIncomeDesc(claimDetailVo.getIncomeDesc());//收益说明
							product.setAddYield(claimDetailVo.getAddYield());//附加收益
							product.setCreateTime(time);//创建时间
							product.setCompletedProgress(new BigDecimal(0.00));//完成进度[默认0.00%]
							product.setTempId(tempId);//产品模板ID
							product.setProdKind(tmptForm.getPROD_TYPE());//产品类型
							if(DictConstant.SetType.HADSETTED.getCode().equals(tmptForm.getSETYPE_OPEN_USERS())){//已设置取值
								product.setOpenCustomer(tmptForm.getOPEN_USERS());//开放用户
							}
							if(DictConstant.SetType.HADSETTED.getCode().equals(tmptForm.getSETYPE_USERS_SRC())){//已设置取值
								product.setCustomerOrigin(tmptForm.getUSERS_SRC());//用户来源
							}
							product.setValidTerm(Integer.valueOf(tmptForm.getTRANS_VALID_DURATION()));//有效期限
							if(DictConstant.SetType.HADSETTED.getCode().equals(tmptForm.getSETYPE_TRANS_VALID_DURATION())){//已设置为Y
								product.setIsValidTerm(DictConstant.FlagStatus.Y.toString());//是否限制有效期限(Y)
								//product.setIsValidTerm(tmptForm.getSETYPE_TRANS_VALID_DURATION());//是否限制有效期限
							}
							if(DictConstant.SetType.INVALID.getCode().equals(tmptForm.getSETYPE_TRANS_VALID_DURATION())){//无效项为N
								product.setIsValidTerm(DictConstant.FlagStatus.N.toString());//是否限制有效期限(N)
								//product.setIsValidTerm(tmptForm.getSETYPE_TRANS_VALID_DURATION());//是否限制有效期限
							}
							if(!StringUtil.isEmpty(tmptForm.getSINGLE_INVEST_MIN())){
								BigDecimal minAmount=new BigDecimal(tmptForm.getSINGLE_INVEST_MIN());
								product.setMinAmount(minAmount);//起售金额
							}
							if(!StringUtil.isEmpty(tmptForm.getSINGLE_INVEST_MAX())){
								BigDecimal maxAmount=new BigDecimal(tmptForm.getSINGLE_INVEST_MAX());
								product.setMaxAmount(maxAmount);//购买上线
							}
							if(!StringUtil.isEmpty(tmptForm.getINCREMENT_AMT())){
								BigDecimal stepAmount=new BigDecimal(tmptForm.getINCREMENT_AMT());
								product.setStepAmount(stepAmount);//递增金额
							}
							product.setOperator(userId);//操作人
							if(!StringUtil.isEmpty(tmptForm.getMIN_HOLDE_PERIOD())){
								product.setMinHoldTerm(Integer.valueOf(tmptForm.getMIN_HOLDE_PERIOD()));//最低持有期限
							}
							if(DictConstant.SetType.HADSETTED.getCode().equals(tmptForm.getSETYPE_MIN_HOLDE_PERIOD_CYCLE())){//已设置取值
								product.setHoldTermType(tmptForm.getMIN_HOLDE_PERIOD_CYCLE());//持有期限周期
							}
							product.setValidTermType(tmptForm.getTRANS_VALID_CYCLE());//有效期限周期
							product.setStartSellTime(time);//起售时间
							Date endSellTime = acquireEndSellTime(time, tmptForm);
							product.setEndSellTime(endSellTime);//停售时间
							product.setReleaseTime(time);//发布时间
							product.setExpireStatus(DictConstant.FlagStatus.N.toString());//到期状态
							product.setExpireTime(claimDetailVo.getExpireDate());//产品到期日
							result = productDao.saveProduct(product);
							if(result > 0){ 
								//添加产品关联协议表(p2p_prod_relative_prot)
								if(productProtocols.size() > 0 && null != productProtocols){
									List<ProdRelativeProt> prp = formatTempProt(prodCode,productProtocols);
									result = prodRelativeProtDao.saveProdRelativeProt(prp);
								}
							}
						} catch (Exception e) {
							e.printStackTrace();
						}
					}
				}
			}
		}
		return result;
	}
	
	/**
	 * 获取协议ID
	 * @param prodCode
	 * @param productProtocols
	 * @return
	 */
	private List<ProdRelativeProt> formatTempProt(String prodCode, List<ProductProtocol> productProtocols) {
		List<ProdRelativeProt> tpList = new ArrayList<ProdRelativeProt>();
		for (ProductProtocol productProtocol : productProtocols) {
			ProdRelativeProt tp = new ProdRelativeProt();
			tp.setProd(prodCode);
			tp.setProtId(productProtocol.getId());
			tpList.add(tp);
		}
		return tpList;
	}
	
	/**
	 * 获取停售时间
	 * @param time
	 * @param tmptForm
	 * @return
	 */
	private Date acquireEndSellTime(Date time, TransProdTmptForm tmptForm){
		Date endSellTime = null;
		try {
			//有效时长
			String transValidDuration =  tmptForm.getTRANS_VALID_DURATION();
			if(!StringUtil.isEmpty(transValidDuration)){
				//有效时长
				int validTerm = Integer.valueOf(transValidDuration);
				//有效期限周期
				String transValidCycle = tmptForm.getTRANS_VALID_CYCLE();
				//格式化
				java.text.DateFormat sft = new java.text.SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
				String s = sft.format(time);
				Calendar rightNow = Calendar.getInstance();
				Date dt = sft.parse(s);
				rightNow.setTime(dt);
		        if(DictConstant.TimeUit.Y.getCode().equalsIgnoreCase(transValidCycle)){
					rightNow.add(Calendar.YEAR,Integer.valueOf(validTerm));//日期加指定年数
				}
				if(DictConstant.TimeUit.M.getCode().equalsIgnoreCase(transValidCycle)){
					rightNow.add(Calendar.MONTH,Integer.valueOf(validTerm));//日期加指定月数
				}
				if(DictConstant.TimeUit.D.getCode().equalsIgnoreCase(transValidCycle)){
					rightNow.add(Calendar.DAY_OF_YEAR,Integer.valueOf(validTerm));//日期加指定天数
				}
				//停售时间
				endSellTime = rightNow.getTime();  
				//停售时间格式化
				//String reStr = sft.format(dt1); 
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return endSellTime;
	}

	@Override
	public JsonResult refusedPassClaim(Long userId, String serialNo, String remark) {
		JsonResult jsonResult=new JsonResult(false,"操作失败!");
		//影响行数
		int result = 0;
		//根据债权申请编号查询信息
		TransferApply transferApply = transferApplyDao.selectTransferApplyBySerialNo(serialNo);
		if(!"".equals(transferApply) && transferApply != null){
			if(DictConstant.TranferStatus.NO_PASS.getCode().equalsIgnoreCase(transferApply.getTranferStatus())){
				//更新转让状态(根据自转债权流水号更新转让状态)
				TransferApply apply = new TransferApply();
				apply.setSerialNo(serialNo);
				apply.setTranferStatus(DictConstant.TranferStatus.NO_PASS.getCode());
				result = transferApplyDao.updateStatusBySerialNo(apply);
				if(result > 0){
					//添加债权申请操作日志
					result = addaAplyLog(userId, remark, transferApply,"NO_PASS");
					if(result >0){
						jsonResult=new JsonResult(true,"操作成功!");
					}else{
						jsonResult=new JsonResult(false,"添加债权申请操作日志失败!");
					}
				}else{
					jsonResult=new JsonResult(false,"更新转让状态失败!");
				}
			}else{
				jsonResult=new JsonResult(false,"不可重复审核");
			}
		}
		return jsonResult;
	}

	@Override
	public TransApplyLog selectNoPassInfo(String serialNo) {
		return transApplyLogDao.getNoPassInfo(serialNo);
	}
	
	
}
